package cn.sdhuijin.vms.controller;

import java.util.List;

import javax.inject.Inject;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.sdhuijin.vms.controller.comand.PageInfo;
import cn.sdhuijin.vms.model.Organization;
import cn.sdhuijin.vms.model.Person;
import cn.sdhuijin.vms.model.User;
import cn.sdhuijin.vms.service.IPersonService;
import cn.sdhuijin.vms.util.OrgUtil;

@Controller
@RequestMapping("/person")
public class PersonController {
	final Logger logger = LoggerFactory.getLogger(PersonController.class);
	@Inject
	private IPersonService personService;

	@RequestMapping(value = "", method = RequestMethod.GET)
	public String show() {
		return "person/show";
	}

	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public String list(PageInfo pageInfo, Model model) {
		Page<Person> page;
		Subject currentUser = SecurityUtils.getSubject();
		if (currentUser.hasRole("admin")) {
			page = personService
					.getList(pageInfo.getPage(), pageInfo.getRows());
		} else {
			Organization org = ((User) currentUser.getPrincipal())
					.getOrganization();
			page = personService.getListByOrgIds(OrgUtil.getAllIds(org),
					pageInfo.getPage(), pageInfo.getRows());
		}
		model.addAttribute("page", page);
		return "person/list";
	}

	@RequestMapping(value = "/add", method = RequestMethod.GET)
	public String add(@ModelAttribute Person person) {
		return "person/add";
	}

	@RequestMapping(value = { "/add" }, method = RequestMethod.POST)
	@ResponseBody
	public JsonResult add(@Validated Person person, BindingResult error) {
		JsonResult jr = new JsonResult();
		StringBuffer sb = new StringBuffer();
		if (error.hasErrors()) {
			jr.setSuccess(false);
			List<FieldError> fes = error.getFieldErrors();
			for (FieldError fe : fes) {
				sb.append(fe.getDefaultMessage()).append(" ");
			}
		} else {
			Subject currentUser = SecurityUtils.getSubject();
			if (currentUser.hasRole("admin")) {
				personService.save(person);
			} else {
				User master = (User) currentUser.getPrincipal();
				person.setMaster(master);
				personService.save(person);
			}

		}
		jr.setMessage(sb.toString());
		return jr;
	}

	@RequestMapping(value = "/update/{personId}", method = RequestMethod.GET)
	public String update(@PathVariable Long personId, Model model) {
		model.addAttribute(personService.load(personId));
		return "person/update";
	}

	@RequestMapping(value = { "/update/{personId}" }, method = RequestMethod.POST)
	@ResponseBody
	public JsonResult update(@PathVariable Long personId,
			@Validated Person person, BindingResult error) {
		JsonResult jr = new JsonResult();
		StringBuffer sb = new StringBuffer();
		if (error.hasErrors()) {
			jr.setSuccess(false);
			List<FieldError> fes = error.getFieldErrors();
			for (FieldError fe : fes) {
				sb.append(fe.getDefaultMessage()).append(" ");
			}
		} else {
			Person temp = personService.load(personId);
			temp.setPhone(person.getPhone());
			temp.getCard().setNumber(person.getCard().getNumber());
			temp.setOrganization(person.getOrganization());
			personService.save(temp);
		}
		jr.setMessage(sb.toString());
		return jr;
	}

	@RequestMapping(value = { "/delete/{personId}" }, method = RequestMethod.POST)
	@ResponseBody
	public JsonResult delete(@PathVariable Long personId) {
		JsonResult jr = new JsonResult();
		jr.setSuccess(true);
		try {
			personService.delete(personId);
		} catch (Exception e) {
			jr.setMessage(e.getMessage());
			jr.setSuccess(false);
		}
		return jr;
	}

}
